package com.yuerlive.rainbow.module.search;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.TextWatcherAdapter;
import com.yuerlive.rainbow.controller.LiveRoomController;
import com.yuerlive.rainbow.entity.Anchor;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.UserInfo;
import com.yuerlive.rainbow.module.homepage.HomePageActivity;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.search.adapter.SearchAdapter;
import com.yuerlive.rainbow.module.search.presenter.SearchContract;
import com.yuerlive.rainbow.module.search.presenter.SearchPresenter;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.Utils;
import com.yuerlive.rainbow.widget.CircleImageView;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017/5/18.
 */

public class SearchActivity extends BaseActivity implements SearchContract.View {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    LinearLayoutManager layoutManager;
    List<Anchor> mDatas = new ArrayList<>();
    List<Anchor> mOtherSearchs = new ArrayList<>();
    SearchAdapter adapter;
    SearchContract.Presenter presenter;
    @BindView(R.id.llOthers)
    LinearLayout llOthers;
    @BindView(R.id.editSearch)
    EditText editSearch;
    @BindView(R.id.ivClear)
    ImageView ivClear;

    CustomDialog userCard;

    //用户卡片
    TextView tvNickName;
    TextView tvLevel;
    TextView tvId;
    TextView tvWords;
    TextView tvFollowCount;
    TextView tvFollow;
    TextView tvFansCount;
    TextView tvCharmCount;
    LinearLayout llCount;
    CircleImageView imgHeader;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initViews() {
        presenter = new SearchPresenter(this);
        presenter.getOthersSearch();
        layoutManager = new LinearLayoutManager(this);
        recycleView.setLayoutManager(layoutManager);

        adapter = new SearchAdapter(this, mDatas);
        adapter.setOnItemClickListener((v, p) -> {
            switch (v.getId()) {
                case R.id.tvFollow:  //关注
                    presenter.subscribeUp(mDatas.get(p).getId(), p);
                    break;
                case R.id.imgHeader:
                    Intent intent2 = new Intent();
                    intent2.setClass(this, HomePageActivity.class);
                    intent2.putExtra("otherId", mDatas.get(p).getId());
                    jumpToActivity(intent2);
                 //   presenter.getUserInfo(mDatas.get(p).getId(), p);
                    break;
                default:
                    Anchor info = mDatas.get(p);
                    if (info.getState()!=0) {
                        Intent intent = new Intent();
                        intent.setClass(this, LiveRoomActivity.class);
                        intent.putExtra("liveId", info.getLiveId());
                        intent.putExtra("chatroomId", info.getChatRoomId());
                        intent.putExtra("liveCover", info.getLiveIcon());
                        LiveRoomController.getInstance().enterLiveRoom(this,intent);
                    }else{
                        Intent intent = new Intent();
                        intent.setClass(this, HomePageActivity.class);
                        intent.putExtra("otherId", info.getId());
                        jumpToActivity(intent);
                    }
            }
        });
        recycleView.setAdapter(adapter);

        editSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (!TextUtil.isEmpty(v.getText().toString())) {
                    presenter.search(v.getText().toString());
                }
                return true;
            }
            return false;
        });
        editSearch.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (s.length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
            }
        });

        initUserCard();
    }


    @Override
    public void setPresenter(SearchContract.Presenter presenter) {
        super.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


    @Override
    public void showOthersSearch(List<Anchor> results) {
        if (results == null)return;
        mOtherSearchs = results;
        mDatas.clear();
        llOthers.setVisibility(View.VISIBLE);
        mDatas.addAll(results);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showSearchResults(List<Anchor> results) {
        mDatas.clear();
        llOthers.setVisibility(View.GONE);
        if (results != null) {
            mDatas.addAll(results);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showSubscribeResult(int code, int pos) {
        Anchor anchor = mDatas.get(pos);
        if (code == 0) {
            anchor.setIsSubscribe((anchor.getIsSubscribe() + 1) % 2);
            if (anchor.getIsSubscribe() == 1) {
                showToast("关注成功");
                Observerable.getInstance().notifyChange(ObserverableType.ATTENTION, 1);
                mDatas.set(pos, anchor);
                if (userCard.isShowing()) {
                    tvFollow.setText("已关注");
                    tvFollow.setTextColor(getResources().getColor(R.color.text_livecard_Id));
                    tvFollow.setBackgroundResource(R.drawable.btn_recharge_gray);
                    tvFansCount.setText(String.valueOf(
                            Integer.parseInt(tvFansCount.getText().toString()) + 1
                    ));
                }
            } else {
                showToast("取消关注成功");
                Observerable.getInstance().notifyChange(ObserverableType.ATTENTION, -1);
                if (userCard.isShowing()) {
                    tvFollow.setText("+ 关注");
                    tvFollow.setTextColor(getResources().getColor(R.color.white));
                    tvFollow.setBackgroundResource(R.drawable.btn_recharge);
                    tvFansCount.setText(String.valueOf(
                            Integer.parseInt(tvFansCount.getText().toString()) - 1
                    ));
                }
            }


            adapter.notifyItemChanged(pos);
        } else {
            if (anchor.getIsSubscribe() == 1) {
                showToast("关注失败");
            } else {
                showToast("取消关注失败");
            }
        }
    }

    @Override
    public void showUserInfo(BaseData<UserInfo> data, int pos) {
        userCard.show();
        UserInfo info = data.getObject();
        tvWords.setText(TextUtil.isEmpty(info.getPersonalsignature()) ? "这家伙很懒，啥都没说~"
                : info.getPersonalsignature());
        tvCharmCount.setText(String.valueOf(info.getCharmtotalvalue()));
        tvFansCount.setText(String.valueOf(info.getFans()));
        tvFollowCount.setText(String.valueOf(info.getSubscribenum()));
        tvId.setText(String.valueOf(info.getId()));
        tvNickName.setText(info.getNickname());
        tvNickName.setCompoundDrawablesWithIntrinsicBounds(0, 0, info.getSex() == 0 ? R.drawable.icon_boy : R.drawable.icon_girl, 0);
        tvLevel.setText(String.valueOf(info.getLv()));
        Utils.setLevel(tvLevel, info.getLv());
        GlideUtil.load(this, info.getIcon(), imgHeader);
        if (info.getIsSubscribe() == 0) {
            tvFollow.setText("+ 关注");
            tvFollow.setTextColor(getResources().getColor(R.color.white));
            tvFollow.setBackgroundResource(R.drawable.btn_recharge);
        } else {
            tvFollow.setText("已关注");
            tvFollow.setTextColor(getResources().getColor(R.color.text_livecard_Id));
            tvFollow.setBackgroundResource(R.drawable.btn_recharge_gray);
        }
        tvFollow.setOnClickListener((view) -> {
            presenter.subscribeUp(mDatas.get(pos).getId(), pos);
        });


    }

    private void initUserCard() {
        if (userCard == null) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.layout_usercard, null);
            userCard = new CustomDialog(mActivity, v, true);
            imgHeader = (CircleImageView) v.findViewById(R.id.imgHeader);
            tvCharmCount = (TextView) v.findViewById(R.id.tvCharmCount);
            tvFansCount = (TextView) v.findViewById(R.id.tvFansCount);
            tvId = (TextView) v.findViewById(R.id.tvId);
            tvNickName = (TextView) v.findViewById(R.id.tvNickName);
            tvWords = (TextView) v.findViewById(R.id.tvWords);
            tvLevel = (TextView) v.findViewById(R.id.tvLevel);
            tvFollowCount = (TextView) v.findViewById(R.id.tvFollowCount);
            tvFollow = (TextView) v.findViewById(R.id.tvFollow);
            v.findViewById(R.id.ivCancel).setOnClickListener((view) ->
                    userCard.hide());
            userCard.hide();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        userCard.dismiss();
    }

    @OnClick({R.id.cancel, R.id.ivClear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                onBackPressed();
                break;
            case R.id.ivClear:
                editSearch.setText("");
                mDatas.clear();
                mDatas.addAll(mOtherSearchs);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
